package com.thghh.fsbrowser.fs;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;

public class FSInputStream extends InputStream {

	InputStream wrappedStream;
	IFileSystem fs;
	boolean closed;
	long pos;
	
	public FSInputStream(FilePath fp) throws IOException {
		this(fp.fs().open(fp), fp.fs());
	}

	FSInputStream(InputStream stream, IFileSystem fs) {
		if (stream == null) {
			throw new IllegalArgumentException("Null InputStream");
		}
		if (fs == null) {
			throw new IllegalArgumentException("FTP client null or not connected");
		}
		this.wrappedStream = stream;
		this.fs = fs;
		this.pos = 0;
		this.closed = false;
	}

	public long getPos() {
		return pos;
	}

	public synchronized int read() throws IOException {
		if (closed) {
			throw new IOException("Stream closed");
		}

		int byteRead = wrappedStream.read();
		if (byteRead >= 0) {
			pos++;
		}
		return byteRead;
	}

	public synchronized int read(byte buf[], int off, int len) throws IOException {
		if (closed) {
			throw new IOException("Stream closed");
		}

		int result = wrappedStream.read(buf, off, len);
		if (result > 0) {
			pos += result;
		}
		return result;
	}

	public synchronized void close() throws IOException {
		if (closed) {
			throw new IOException("Stream closed");
		}
		wrappedStream.close();
		super.close();
		closed = true;
		if (!fs.isConnected()) {
			throw new ConnectException("fs not connected");
		}
		fs.close();
	}
}
